package com.ruoyi.paint.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.paint.admin.domain.ImExportDto.TqSchemetintsAllImport;
import com.ruoyi.paint.admin.domain.ImExportDto.TqSchemetintsImport;
import com.ruoyi.paint.admin.domain.TqCars;
import com.ruoyi.paint.admin.domain.TqColorschemes;
import com.ruoyi.paint.admin.domain.TqSchemetints;
import com.ruoyi.paint.admin.domain.TqTints;
import com.ruoyi.paint.admin.mapper.TqSchemetintsMapper;
import com.ruoyi.paint.admin.service.ITqCarsService;
import com.ruoyi.paint.admin.service.TqColorschemesService;
import com.ruoyi.paint.admin.service.TqSchemetintsService;
import com.ruoyi.paint.admin.service.TqTintsService;
import com.ruoyi.paint.admin.utils.BeanCopyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @author Asus
* @description 针对表【tq_schemetints(配色方案色母关联表)】的数据库操作Service实现
* @createDate 2024-07-03 11:58:47
*/
@Service
public class TqSchemetintsServiceImpl extends ServiceImpl<TqSchemetintsMapper, TqSchemetints>
    implements TqSchemetintsService{

    @Autowired
    private ITqCarsService tqCarsService;
    @Autowired
    private TqTintsService tqTintsService;
    @Autowired
    private TqColorschemesService tqColorschemesService;

    @Override
    public List<String> saveBatchSchemeTint(List<TqSchemetintsImport> collectedSchemeTint) {
        List<String> failureMessages = new ArrayList<>();

        for (TqSchemetintsImport importData : collectedSchemeTint) {
            try {
                Long carId = findCarId(importData);
                List<TqColorschemes> colorschemesId = findColorschemeId(carId);

                if (colorschemesId == null) {
                    log.error("未能找到对应的颜色方案记录，创建新的颜色方案记录");
                    throw new RuntimeException("未能找到对应的颜色方案记录，创建新的颜色方案记录");
                }

                saveTintForScheme(importData, carId, "配色方案一");
                saveTintForScheme(importData, carId, "配色方案二");  // 假设每个数据项都包含两个方案

            } catch (Exception e) {
                log.error("处理数据项时发生错误:"+importData+"错误信息："+e.getMessage());
                failureMessages.add("处理数据失败: " + importData.getTitle() + ", 错误: " + e.getMessage());
            }
        }
        failureMessages.add("色母关联导入成功：" + (collectedSchemeTint.size() - failureMessages.size()) + "条数据");
        return failureMessages;
    }



    private void saveTintForScheme(TqSchemetintsImport importData, Long carId, String title) {
        if (importData.getTitle().equals(title)) {
            Long colorschemeIds = findColorschemeIds(carId, title);
            Long tintId = resolveAndSaveTint(importData);
            TqSchemetints tqSchemetints = BeanCopyUtils.copyBean(importData, TqSchemetints.class);
            tqSchemetints.setTintId(tintId);
            tqSchemetints.setTotal(importData.getTotal());
            tqSchemetints.setSchemeId(colorschemeIds);
            save(tqSchemetints);
        }
    }


    private Long findCarId(TqSchemetintsImport importData) {
        LambdaQueryWrapper<TqCars> carWrapper = new LambdaQueryWrapper<>();
        carWrapper.eq(TqCars::getBrand, importData.getBrand())
                .eq(TqCars::getModel, importData.getModel())
                .eq(TqCars::getColorName, importData.getColorName());

        List<TqCars> list = tqCarsService.list(carWrapper);
        if (list == null) {
            log.error("处理颜色方案细节数据时发生错误");
//            failureMessages.add("错误原因：" + "关联表中车辆信息填写有误");
            throw new RuntimeException("未能找到对应的车辆信息记录，创建新的颜色方案记录");
        }
        return list.get(0).getId();
    }

    private List<TqColorschemes> findColorschemeId(Long carId) {
        LambdaQueryWrapper<TqColorschemes> colorSchemeWrapper = new LambdaQueryWrapper<>();
        colorSchemeWrapper.eq(TqColorschemes::getCarId, carId);
        // 可能还需要根据其他属性来精确匹配颜色方案，根据实际情况调整查询条件
        List<TqColorschemes> list = tqColorschemesService.list(colorSchemeWrapper);
        if (list == null) {
            log.error("未能找到对应的颜色方案记录，创建新的颜色方案记录");
            throw new RuntimeException("未能找到对应的颜色方案记录，创建新的颜色方案记录");
        }
        return list;

    }

    private Long findColorschemeIds(Long carId, String title) throws RuntimeException{
        Map<String, Long> longList = new HashMap<>();
        LambdaQueryWrapper<TqColorschemes> colorSchemeWrapper = new LambdaQueryWrapper<>();
        colorSchemeWrapper.eq(TqColorschemes::getCarId, carId).eq(TqColorschemes::getTitle, title);
        // 可能还需要根据其他属性来精确匹配颜色方案，根据实际情况调整查询条件
        TqColorschemes colorschemes = tqColorschemesService.getOne(colorSchemeWrapper);
        if (colorschemes == null) {
            log.error("未能找到对应的颜色方案记录，创建新的颜色方案记录");
            throw new RuntimeException("未能找到对应的颜色方案记录，创建新的颜色方案记录");
        }
        return colorschemes.getId();
    }

    private Long resolveAndSaveTint(TqSchemetintsImport importData) {
        String tintCode = importData.getTintCode();
        List<TqTints> list = tqTintsService.list(new LambdaQueryWrapper<TqTints>().eq(TqTints::getTintCode, tintCode));
        if (list == null) {
            TqTints tqTints = new TqTints();
            tqTints.setTintCode(importData.getTintCode());
            tqTints.setTintName(importData.getTintName());
            tqTintsService.save(tqTints);
            return tqTints.getId();
        } else{
            return list.get(0).getId();
        }
    }


    /**
     * 新加
     * @param collectedSchemeTint 导入数据
     * @return
     */
    @Override
    public String saveBatchSchemeTintAll(List<TqSchemetintsAllImport> collectedSchemeTint) {
        List<String> failureMessages = new ArrayList<>();

        for (TqSchemetintsAllImport importData : collectedSchemeTint) {
                Long carId = findCarIdAll(importData);
                List<TqColorschemes> colorschemesId = findColorschemeId(carId);
                if (colorschemesId == null) {
                    log.error("未能找到对应的颜色方案记录，创建新的颜色方案记录");
                    throw new RuntimeException("未能找到对应的颜色方案记录，创建新的颜色方案记录");
                }

                saveTintForSchemeAll(importData, carId, "配色方案一");
                saveTintForSchemeAll(importData, carId, "配色方案二");
        }
        return "导入配色数量："+collectedSchemeTint.size() ;
    }



    /**
     * 新加
     * @param importData
     * @return
     */
    private Long findCarIdAll(TqSchemetintsAllImport importData) {
        LambdaQueryWrapper<TqCars> carWrapper = new LambdaQueryWrapper<>();
        carWrapper.eq(TqCars::getBrand, importData.getBrand())
                .eq(TqCars::getModel, importData.getModel())
                .eq(TqCars::getColorName, importData.getColorName())
                .eq(TqCars::getYear, importData.getYear())
                .eq(TqCars::getPaintBrand, importData.getPaintBrand());
        List<TqCars> list = tqCarsService.list(carWrapper);
        if (list == null) {
            log.error("处理颜色方案细节数据时发生错误");
            throw new ServiceException("未能找到对应的车辆信息记录，创建新的颜色方案记录" + importData.getTitle() + importData.getBrand() + importData.getModel()
                    + importData.getColorName() + importData.getYear() + importData.getPaintBrand());
        }
        return list.get(0).getId();
    }


    private void saveTintForSchemeAll(TqSchemetintsAllImport importData, Long carId, String title) {
        if (importData.getTitle().equals(title)) {
            Long colorschemeIds = findColorschemeIds(carId, title);
            Long tintId = resolveAndSaveTintAll(importData);
            TqSchemetints tqSchemetints = BeanCopyUtils.copyBean(importData, TqSchemetints.class);
            tqSchemetints.setTintId(tintId);
            tqSchemetints.setSchemeId(colorschemeIds);
            tqSchemetints.setTotal(importData.getTotal());
            save(tqSchemetints);

        }
    }


    private Long resolveAndSaveTintAll(TqSchemetintsAllImport importData) {
        String tintCode = importData.getTintCode();
        List<TqTints> list = tqTintsService.list(new LambdaQueryWrapper<TqTints>()
                .eq(TqTints::getTintCode, tintCode).eq(TqTints::getTintName, importData.getTintName()));
        if ( list.isEmpty()) {
            TqTints tqTints = new TqTints();
            tqTints.setTintCode(importData.getTintCode());
            tqTints.setTintName(importData.getTintName());
            tqTintsService.save(tqTints);
            return tqTints.getId();
        } else{
            return list.get(0).getId();
        }
    }

}




